{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "4embtkV0pNxM"
   },
   "source": [
    "Deep Learning\n",
    "=============\n",
    "\n",
    "Assignment 4\n",
    "------------\n",
    "\n",
    "Previously in `2_fullyconnected.ipynb` and `3_regularization.ipynb`, we trained fully connected networks to classify [notMNIST](http://yaroslavvb.blogspot.com/2011/09/notmnist-dataset.html) characters.\n",
    "\n",
    "The goal of this assignment is make the neural network convolutional."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "cellView": "both",
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     }
    },
    "colab_type": "code",
    "collapsed": true,
    "id": "tm2CQN_Cpwj0"
   },
   "outputs": [],
   "source": [
    "# These are all the modules we'll be using later. Make sure you can import them\n",
    "# before proceeding further.\n",
    "from __future__ import print_function\n",
    "import numpy as np\n",
    "import tensorflow as tf\n",
    "from six.moves import cPickle as pickle\n",
    "from six.moves import range"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "cellView": "both",
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     },
     "output_extras": [
      {
       "item_id": 1
      }
     ]
    },
    "colab_type": "code",
    "collapsed": false,
    "executionInfo": {
     "elapsed": 11948,
     "status": "ok",
     "timestamp": 1446658914837,
     "user": {
      "color": "",
      "displayName": "",
      "isAnonymous": false,
      "isMe": true,
      "permissionId": "",
      "photoUrl": "",
      "sessionId": "0",
      "userId": ""
     },
     "user_tz": 480
    },
    "id": "y3-cj1bpmuxc",
    "outputId": "016b1a51-0290-4b08-efdb-8c95ffc3cd01"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Training set (200000, 28, 28) (200000,)\n",
      "Validation set (10000, 28, 28) (10000,)\n",
      "Test set (10000, 28, 28) (10000,)\n"
     ]
    }
   ],
   "source": [
    "pickle_file = 'notMNIST.pickle'\n",
    "\n",
    "with open(pickle_file, 'rb') as f:\n",
    "    save = pickle.load(f)\n",
    "    train_dataset = save['train_dataset']\n",
    "    train_labels = save['train_labels']\n",
    "    valid_dataset = save['valid_dataset']\n",
    "    valid_labels = save['valid_labels']\n",
    "    test_dataset = save['test_dataset']\n",
    "    test_labels = save['test_labels']\n",
    "    del save  # hint to help gc free up memory\n",
    "    print('Training set', train_dataset.shape, train_labels.shape)\n",
    "    print('Validation set', valid_dataset.shape, valid_labels.shape)\n",
    "    print('Test set', test_dataset.shape, test_labels.shape)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "L7aHrm6nGDMB"
   },
   "source": [
    "Reformat into a TensorFlow-friendly shape:\n",
    "- convolutions need the image data formatted as a cube (width by height by #channels)\n",
    "- labels as float 1-hot encodings."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "cellView": "both",
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     },
     "output_extras": [
      {
       "item_id": 1
      }
     ]
    },
    "colab_type": "code",
    "collapsed": false,
    "executionInfo": {
     "elapsed": 11952,
     "status": "ok",
     "timestamp": 1446658914857,
     "user": {
      "color": "",
      "displayName": "",
      "isAnonymous": false,
      "isMe": true,
      "permissionId": "",
      "photoUrl": "",
      "sessionId": "0",
      "userId": ""
     },
     "user_tz": 480
    },
    "id": "IRSyYiIIGIzS",
    "outputId": "650a208c-8359-4852-f4f5-8bf10e80ef6c"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Training set (200000, 28, 28, 1) (200000, 10)\n",
      "Validation set (10000, 28, 28, 1) (10000, 10)\n",
      "Test set (10000, 28, 28, 1) (10000, 10)\n"
     ]
    }
   ],
   "source": [
    "image_size = 28\n",
    "num_labels = 10\n",
    "num_channels = 1 # grayscale\n",
    "\n",
    "import numpy as np\n",
    "\n",
    "def reformat(dataset, labels):\n",
    "    dataset = dataset.reshape((-1, image_size, image_size, num_channels)).astype(np.float32)\n",
    "    labels = (np.arange(num_labels) == labels[:,None]).astype(np.float32)\n",
    "    return dataset, labels\n",
    "train_dataset, train_labels = reformat(train_dataset, train_labels)\n",
    "valid_dataset, valid_labels = reformat(valid_dataset, valid_labels)\n",
    "test_dataset, test_labels = reformat(test_dataset, test_labels)\n",
    "print('Training set', train_dataset.shape, train_labels.shape)\n",
    "print('Validation set', valid_dataset.shape, valid_labels.shape)\n",
    "print('Test set', test_dataset.shape, test_labels.shape)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "cellView": "both",
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     }
    },
    "colab_type": "code",
    "collapsed": true,
    "id": "AgQDIREv02p1"
   },
   "outputs": [],
   "source": [
    "def accuracy(predictions, labels):\n",
    "    return (100.0 * np.sum(np.argmax(predictions, 1) == np.argmax(labels, 1))\n",
    "          / predictions.shape[0])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "5rhgjmROXu2O"
   },
   "source": [
    "Let's build a small network with two convolutional layers, followed by one fully connected layer. Convolutional networks are more expensive computationally, so we'll limit its depth and number of fully connected nodes."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "cellView": "both",
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     }
    },
    "colab_type": "code",
    "collapsed": true,
    "id": "IZYv70SvvOan"
   },
   "outputs": [],
   "source": [
    "batch_size = 16\n",
    "patch_size = 5\n",
    "depth = 16\n",
    "num_hidden = 64\n",
    "\n",
    "graph = tf.Graph()\n",
    "\n",
    "with graph.as_default():\n",
    "\n",
    "    # Input data.\n",
    "    tf_train_dataset = tf.placeholder(\n",
    "    tf.float32, shape=(batch_size, image_size, image_size, num_channels))\n",
    "    tf_train_labels = tf.placeholder(tf.float32, shape=(batch_size, num_labels))\n",
    "    tf_valid_dataset = tf.constant(valid_dataset)\n",
    "    tf_test_dataset = tf.constant(test_dataset)\n",
    "  \n",
    "    # Variables.\n",
    "    layer1_weights = tf.Variable(tf.truncated_normal(\n",
    "      [patch_size, patch_size, num_channels, depth], stddev=0.1))\n",
    "    layer1_biases = tf.Variable(tf.zeros([depth]))\n",
    "    layer2_weights = tf.Variable(tf.truncated_normal(\n",
    "      [patch_size, patch_size, depth, depth], stddev=0.1))\n",
    "    layer2_biases = tf.Variable(tf.constant(1.0, shape=[depth]))\n",
    "    layer3_weights = tf.Variable(tf.truncated_normal(\n",
    "      [image_size // 4 * image_size // 4 * depth, num_hidden], stddev=0.1))\n",
    "    layer3_biases = tf.Variable(tf.constant(1.0, shape=[num_hidden]))\n",
    "    layer4_weights = tf.Variable(tf.truncated_normal(\n",
    "      [num_hidden, num_labels], stddev=0.1))\n",
    "    layer4_biases = tf.Variable(tf.constant(1.0, shape=[num_labels]))\n",
    "  \n",
    "    # Model.\n",
    "    def model(data):\n",
    "        conv = tf.nn.conv2d(data, layer1_weights, [1, 2, 2, 1], padding='SAME')\n",
    "        hidden = tf.nn.relu(conv + layer1_biases)\n",
    "        conv = tf.nn.conv2d(hidden, layer2_weights, [1, 2, 2, 1], padding='SAME')\n",
    "        hidden = tf.nn.relu(conv + layer2_biases)\n",
    "        shape = hidden.get_shape().as_list()\n",
    "        reshape = tf.reshape(hidden, [shape[0], shape[1] * shape[2] * shape[3]])\n",
    "        hidden = tf.nn.relu(tf.matmul(reshape, layer3_weights) + layer3_biases)\n",
    "        return tf.matmul(hidden, layer4_weights) + layer4_biases\n",
    "  \n",
    "    # Training computation.\n",
    "    logits = model(tf_train_dataset)\n",
    "    loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits, tf_train_labels))\n",
    "    \n",
    "    # Optimizer.\n",
    "    optimizer = tf.train.GradientDescentOptimizer(0.05).minimize(loss)\n",
    "  \n",
    "    # Predictions for the training, validation, and test data.\n",
    "    train_prediction = tf.nn.softmax(logits)\n",
    "    valid_prediction = tf.nn.softmax(model(tf_valid_dataset))\n",
    "    test_prediction = tf.nn.softmax(model(tf_test_dataset))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "cellView": "both",
    "colab": {
     "autoexec": {
      "startup": false,
      "wait_interval": 0
     },
     "output_extras": [
      {
       "item_id": 37
      }
     ]
    },
    "colab_type": "code",
    "collapsed": false,
    "executionInfo": {
     "elapsed": 63292,
     "status": "ok",
     "timestamp": 1446658966251,
     "user": {
      "color": "",
      "displayName": "",
      "isAnonymous": false,
      "isMe": true,
      "permissionId": "",
      "photoUrl": "",
      "sessionId": "0",
      "userId": ""
     },
     "user_tz": 480
    },
    "id": "noKFb2UovVFR",
    "outputId": "28941338-2ef9-4088-8bd1-44295661e628"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Initialized\n",
      "Minibatch loss at step 0: 6.322746\n",
      "Minibatch accuracy: 6.2%\n",
      "Validation accuracy: 10.0%\n",
      "Minibatch loss at step 50: 2.159534\n",
      "Minibatch accuracy: 12.5%\n",
      "Validation accuracy: 42.2%\n",
      "Minibatch loss at step 100: 1.275694\n",
      "Minibatch accuracy: 68.8%\n",
      "Validation accuracy: 65.8%\n",
      "Minibatch loss at step 150: 1.091493\n",
      "Minibatch accuracy: 75.0%\n",
      "Validation accuracy: 71.3%\n",
      "Minibatch loss at step 200: 0.495773\n",
      "Minibatch accuracy: 75.0%\n",
      "Validation accuracy: 77.1%\n",
      "Minibatch loss at step 250: 1.370594\n",
      "Minibatch accuracy: 68.8%\n",
      "Validation accuracy: 75.9%\n",
      "Minibatch loss at step 300: 1.029788\n",
      "Minibatch accuracy: 62.5%\n",
      "Validation accuracy: 78.6%\n",
      "Minibatch loss at step 350: 1.155066\n",
      "Minibatch accuracy: 68.8%\n",
      "Validation accuracy: 78.5%\n",
      "Minibatch loss at step 400: 0.929617\n",
      "Minibatch accuracy: 75.0%\n",
      "Validation accuracy: 78.6%\n",
      "Minibatch loss at step 450: 0.423272\n",
      "Minibatch accuracy: 87.5%\n",
      "Validation accuracy: 79.9%\n",
      "Minibatch loss at step 500: 0.415235\n",
      "Minibatch accuracy: 87.5%\n",
      "Validation accuracy: 77.7%\n",
      "Minibatch loss at step 550: 0.953014\n",
      "Minibatch accuracy: 75.0%\n",
      "Validation accuracy: 80.5%\n",
      "Minibatch loss at step 600: 0.873650\n",
      "Minibatch accuracy: 75.0%\n",
      "Validation accuracy: 80.8%\n",
      "Minibatch loss at step 650: 0.788326\n",
      "Minibatch accuracy: 75.0%\n",
      "Validation accuracy: 81.3%\n",
      "Minibatch loss at step 700: 0.727097\n",
      "Minibatch accuracy: 75.0%\n",
      "Validation accuracy: 82.1%\n",
      "Minibatch loss at step 750: 0.477610\n",
      "Minibatch accuracy: 93.8%\n",
      "Validation accuracy: 81.8%\n",
      "Minibatch loss at step 800: 1.202713\n",
      "Minibatch accuracy: 68.8%\n",
      "Validation accuracy: 81.8%\n",
      "Minibatch loss at step 850: 0.398247\n",
      "Minibatch accuracy: 81.2%\n",
      "Validation accuracy: 82.4%\n",
      "Minibatch loss at step 900: 0.138772\n",
      "Minibatch accuracy: 100.0%\n",
      "Validation accuracy: 82.8%\n",
      "Minibatch loss at step 950: 0.873386\n",
      "Minibatch accuracy: 87.5%\n",
      "Validation accuracy: 82.5%\n",
      "Minibatch loss at step 1000: 0.585691\n",
      "Minibatch accuracy: 87.5%\n",
      "Validation accuracy: 82.2%\n",
      "Test accuracy: 89.3%\n"
     ]
    }
   ],
   "source": [
    "num_steps = 1001\n",
    "\n",
    "with tf.Session(graph=graph) as session:\n",
    "    tf.initialize_all_variables().run()\n",
    "    print('Initialized')\n",
    "    for step in range(num_steps):\n",
    "        offset = (step * batch_size) % (train_labels.shape[0] - batch_size)\n",
    "        batch_data = train_dataset[offset:(offset + batch_size), :, :, :]\n",
    "        batch_labels = train_labels[offset:(offset + batch_size), :]\n",
    "        feed_dict = {tf_train_dataset : batch_data, tf_train_labels : batch_labels}\n",
    "        _, l, predictions = session.run(\n",
    "          [optimizer, loss, train_prediction], feed_dict=feed_dict)\n",
    "        if (step % 50 == 0):\n",
    "            print('Minibatch loss at step %d: %f' % (step, l))\n",
    "            print('Minibatch accuracy: %.1f%%' % accuracy(predictions, batch_labels))\n",
    "            print('Validation accuracy: %.1f%%' % accuracy(\n",
    "            valid_prediction.eval(), valid_labels))\n",
    "    print('Test accuracy: %.1f%%' % accuracy(test_prediction.eval(), test_labels))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "KedKkn4EutIK"
   },
   "source": [
    "---\n",
    "Problem 1\n",
    "---------\n",
    "\n",
    "The convolutional model above uses convolutions with stride 2 to reduce the dimensionality. Replace the strides by a max pooling operation (`nn.max_pool()`) of stride 2 and kernel size 2.\n",
    "\n",
    "---"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "batch_size = 16\n",
    "patch_size = 5\n",
    "depth = 16\n",
    "num_hidden = 64\n",
    "\n",
    "graph = tf.Graph()\n",
    "\n",
    "with graph.as_default():\n",
    "\n",
    "    # Input data.\n",
    "    tf_train_dataset = tf.placeholder(tf.float32, shape=(batch_size, image_size, image_size, num_channels))\n",
    "    tf_train_labels = tf.placeholder(tf.float32, shape=(batch_size, num_labels))\n",
    "    tf_valid_dataset = tf.constant(valid_dataset)\n",
    "    tf_test_dataset = tf.constant(test_dataset)\n",
    "  \n",
    "    # Variables.\n",
    "    layer1_weights = tf.Variable(tf.truncated_normal([patch_size, patch_size, num_channels, depth], stddev=0.1))\n",
    "    layer1_biases = tf.Variable(tf.zeros([depth]))\n",
    "    layer2_weights = tf.Variable(tf.truncated_normal(\n",
    "      [patch_size, patch_size, depth, depth], stddev=0.1))\n",
    "    layer2_biases = tf.Variable(tf.constant(1.0, shape=[depth]))\n",
    "    layer3_weights = tf.Variable(tf.truncated_normal(\n",
    "      [image_size // 4 * image_size // 4 * depth, num_hidden], stddev=0.1))\n",
    "    layer3_biases = tf.Variable(tf.constant(1.0, shape=[num_hidden]))\n",
    "    layer4_weights = tf.Variable(tf.truncated_normal(\n",
    "      [num_hidden, num_labels], stddev=0.1))\n",
    "    layer4_biases = tf.Variable(tf.constant(1.0, shape=[num_labels]))\n",
    "  \n",
    "    # Model.\n",
    "    def model(data):\n",
    "        conv1 = tf.nn.conv2d(data, layer1_weights, [1, 1, 1, 1], padding='SAME')\n",
    "        bias1 = tf.nn.relu(conv1 + layer1_biases)\n",
    "        pool1 = tf.nn.max_pool(bias1, [1, 2, 2, 1], [1, 2, 2, 1], padding='SAME')\n",
    "        conv2 = tf.nn.conv2d(pool1, layer2_weights, [1, 1, 1, 1], padding='SAME')\n",
    "        bias2 = tf.nn.relu(conv2 + layer2_biases)\n",
    "        pool2 = tf.nn.max_pool(bias2, [1, 2, 2, 1], [1, 2, 2, 1], padding='SAME')\n",
    "        shape = pool2.get_shape().as_list()\n",
    "        reshape = tf.reshape(pool2, [shape[0], shape[1] * shape[2] * shape[3]])\n",
    "        hidden = tf.nn.relu(tf.matmul(reshape, layer3_weights) + layer3_biases)\n",
    "        return tf.matmul(hidden, layer4_weights) + layer4_biases\n",
    "  \n",
    "    # Training computation.\n",
    "    logits = model(tf_train_dataset)\n",
    "    loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits, tf_train_labels))\n",
    "    \n",
    "    # Optimizer.\n",
    "    optimizer = tf.train.GradientDescentOptimizer(0.05).minimize(loss)\n",
    "  \n",
    "    # Predictions for the training, validation, and test data.\n",
    "    train_prediction = tf.nn.softmax(logits)\n",
    "    valid_prediction = tf.nn.softmax(model(tf_valid_dataset))\n",
    "    test_prediction = tf.nn.softmax(model(tf_test_dataset))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Initialized\n",
      "Minibatch loss at step 0: 2.988756\n",
      "Minibatch accuracy: 12.5%\n",
      "Validation accuracy: 8.9%\n",
      "Minibatch loss at step 50: 1.970893\n",
      "Minibatch accuracy: 37.5%\n",
      "Validation accuracy: 50.1%\n",
      "Minibatch loss at step 100: 1.353740\n",
      "Minibatch accuracy: 50.0%\n",
      "Validation accuracy: 64.8%\n",
      "Minibatch loss at step 150: 1.236216\n",
      "Minibatch accuracy: 62.5%\n",
      "Validation accuracy: 72.3%\n",
      "Minibatch loss at step 200: 0.367323\n",
      "Minibatch accuracy: 87.5%\n",
      "Validation accuracy: 77.5%\n",
      "Minibatch loss at step 250: 1.303677\n",
      "Minibatch accuracy: 68.8%\n",
      "Validation accuracy: 77.9%\n",
      "Minibatch loss at step 300: 1.154408\n",
      "Minibatch accuracy: 62.5%\n",
      "Validation accuracy: 79.2%\n",
      "Minibatch loss at step 350: 1.075600\n",
      "Minibatch accuracy: 68.8%\n",
      "Validation accuracy: 80.3%\n",
      "Minibatch loss at step 400: 0.695382\n",
      "Minibatch accuracy: 81.2%\n",
      "Validation accuracy: 79.4%\n",
      "Minibatch loss at step 450: 0.320859\n",
      "Minibatch accuracy: 93.8%\n",
      "Validation accuracy: 81.5%\n",
      "Minibatch loss at step 500: 0.278224\n",
      "Minibatch accuracy: 81.2%\n",
      "Validation accuracy: 80.9%\n",
      "Minibatch loss at step 550: 1.185129\n",
      "Minibatch accuracy: 62.5%\n",
      "Validation accuracy: 80.9%\n",
      "Minibatch loss at step 600: 0.902050\n",
      "Minibatch accuracy: 62.5%\n",
      "Validation accuracy: 82.4%\n",
      "Minibatch loss at step 650: 0.784917\n",
      "Minibatch accuracy: 81.2%\n",
      "Validation accuracy: 82.8%\n",
      "Minibatch loss at step 700: 0.756627\n",
      "Minibatch accuracy: 81.2%\n",
      "Validation accuracy: 83.3%\n",
      "Minibatch loss at step 750: 0.599130\n",
      "Minibatch accuracy: 87.5%\n",
      "Validation accuracy: 83.2%\n",
      "Minibatch loss at step 800: 1.050460\n",
      "Minibatch accuracy: 75.0%\n",
      "Validation accuracy: 82.1%\n",
      "Minibatch loss at step 850: 0.284284\n",
      "Minibatch accuracy: 100.0%\n",
      "Validation accuracy: 83.7%\n",
      "Minibatch loss at step 900: 0.098515\n",
      "Minibatch accuracy: 100.0%\n",
      "Validation accuracy: 84.1%\n",
      "Minibatch loss at step 950: 1.195732\n",
      "Minibatch accuracy: 56.2%\n",
      "Validation accuracy: 83.4%\n",
      "Minibatch loss at step 1000: 0.655579\n",
      "Minibatch accuracy: 87.5%\n",
      "Validation accuracy: 84.3%\n",
      "Test accuracy: 90.5%\n"
     ]
    }
   ],
   "source": [
    "num_steps = 1001\n",
    "\n",
    "with tf.Session(graph=graph) as session:\n",
    "    tf.initialize_all_variables().run()\n",
    "    print('Initialized')\n",
    "    for step in range(num_steps):\n",
    "        offset = (step * batch_size) % (train_labels.shape[0] - batch_size)\n",
    "        batch_data = train_dataset[offset:(offset + batch_size), :, :, :]\n",
    "        batch_labels = train_labels[offset:(offset + batch_size), :]\n",
    "        feed_dict = {tf_train_dataset : batch_data, tf_train_labels : batch_labels}\n",
    "        _, l, predictions = session.run(\n",
    "          [optimizer, loss, train_prediction], feed_dict=feed_dict)\n",
    "        if (step % 50 == 0):\n",
    "            print('Minibatch loss at step %d: %f' % (step, l))\n",
    "            print('Minibatch accuracy: %.1f%%' % accuracy(predictions, batch_labels))\n",
    "            print('Validation accuracy: %.1f%%' % accuracy(\n",
    "            valid_prediction.eval(), valid_labels))\n",
    "    print('Test accuracy: %.1f%%' % accuracy(test_prediction.eval(), test_labels))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "klf21gpbAgb-"
   },
   "source": [
    "---\n",
    "Problem 2\n",
    "---------\n",
    "\n",
    "Try to get the best performance you can using a convolutional net. Look for example at the classic [LeNet5](http://yann.lecun.com/exdb/lenet/) architecture, adding Dropout, and/or adding learning rate decay.\n",
    "\n",
    "---"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# This is useful \n",
    "# https://www.tensorflow.org/versions/master/tutorials/mnist/pros/index.html#build-a-multilayer-convolutional-network"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "batch_size = 16\n",
    "patch_size = 5\n",
    "depth = 16\n",
    "num_hidden = 64\n",
    "\n",
    "graph = tf.Graph()\n",
    "\n",
    "with graph.as_default():\n",
    "\n",
    "    # Input data.\n",
    "    tf_train_dataset = tf.placeholder(\n",
    "    tf.float32, shape=(batch_size, image_size, image_size, num_channels))\n",
    "    tf_train_labels = tf.placeholder(tf.float32, shape=(batch_size, num_labels))\n",
    "    tf_valid_dataset = tf.constant(valid_dataset)\n",
    "    tf_test_dataset = tf.constant(test_dataset)\n",
    "  \n",
    "    # Variables.\n",
    "    layer1_weights = tf.Variable(tf.truncated_normal([patch_size, patch_size, num_channels, depth], stddev=0.1))\n",
    "    layer1_biases = tf.Variable(tf.zeros([depth]))\n",
    "    layer2_weights = tf.Variable(tf.truncated_normal([patch_size, patch_size, depth, depth], stddev=0.1))\n",
    "    layer2_biases = tf.Variable(tf.constant(1.0, shape=[depth]))\n",
    "    size3 = ((image_size - patch_size + 1) // 2 - patch_size + 1) // 2\n",
    "    layer3_weights = tf.Variable(tf.truncated_normal([size3 * size3 * depth, num_hidden], stddev=0.1))\n",
    "    layer3_biases = tf.Variable(tf.constant(1.0, shape=[num_hidden]))\n",
    "    layer4_weights = tf.Variable(tf.truncated_normal([num_hidden, num_labels], stddev=0.1))\n",
    "    layer4_biases = tf.Variable(tf.constant(1.0, shape=[num_labels]))\n",
    "  \n",
    "    # Model.\n",
    "    def model(data):\n",
    "        # C1 input 28 x 28\n",
    "        conv1 = tf.nn.conv2d(data, layer1_weights, [1, 1, 1, 1], padding='VALID')\n",
    "        bias1 = tf.nn.relu(conv1 + layer1_biases)\n",
    "        # S2 input 24 x 24\n",
    "        pool2 = tf.nn.avg_pool(bias1, [1, 2, 2, 1], [1, 2, 2, 1], padding='VALID')\n",
    "        # C3 input 12 x 12\n",
    "        conv3 = tf.nn.conv2d(pool2, layer2_weights, [1, 1, 1, 1], padding='VALID')\n",
    "        bias3 = tf.nn.relu(conv3 + layer2_biases)\n",
    "        # S4 input 8 x 8\n",
    "        pool4 = tf.nn.avg_pool(bias3, [1, 2, 2, 1], [1, 2, 2, 1], padding='VALID')\n",
    "        # F6 input 4 x 4\n",
    "        shape = pool4.get_shape().as_list()\n",
    "        reshape = tf.reshape(pool4, [shape[0], shape[1] * shape[2] * shape[3]])\n",
    "        hidden = tf.nn.relu(tf.matmul(reshape, layer3_weights) + layer3_biases)\n",
    "        return tf.matmul(hidden, layer4_weights) + layer4_biases\n",
    "  \n",
    "    # Training computation.\n",
    "    logits = model(tf_train_dataset)\n",
    "    loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits, tf_train_labels))\n",
    "    \n",
    "    # Optimizer.\n",
    "    optimizer = tf.train.GradientDescentOptimizer(0.05).minimize(loss)\n",
    "  \n",
    "    # Predictions for the training, validation, and test data.\n",
    "    train_prediction = tf.nn.softmax(logits)\n",
    "    valid_prediction = tf.nn.softmax(model(tf_valid_dataset))\n",
    "    test_prediction = tf.nn.softmax(model(tf_test_dataset))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Initialized\n",
      "Minibatch loss at step 0: 2.799783\n",
      "Minibatch accuracy: 12.5%\n",
      "Validation accuracy: 10.0%\n",
      "Minibatch loss at step 200: 0.617947\n",
      "Minibatch accuracy: 81.2%\n",
      "Validation accuracy: 75.3%\n",
      "Minibatch loss at step 400: 0.895411\n",
      "Minibatch accuracy: 68.8%\n",
      "Validation accuracy: 78.0%\n",
      "Minibatch loss at step 600: 1.073238\n",
      "Minibatch accuracy: 62.5%\n",
      "Validation accuracy: 80.7%\n",
      "Minibatch loss at step 800: 0.940057\n",
      "Minibatch accuracy: 81.2%\n",
      "Validation accuracy: 81.1%\n",
      "Minibatch loss at step 1000: 0.749048\n",
      "Minibatch accuracy: 87.5%\n",
      "Validation accuracy: 82.4%\n",
      "Minibatch loss at step 1200: 0.440252\n",
      "Minibatch accuracy: 81.2%\n",
      "Validation accuracy: 83.6%\n",
      "Minibatch loss at step 1400: 0.460307\n",
      "Minibatch accuracy: 93.8%\n",
      "Validation accuracy: 84.2%\n",
      "Minibatch loss at step 1600: 0.860476\n",
      "Minibatch accuracy: 75.0%\n",
      "Validation accuracy: 84.3%\n",
      "Minibatch loss at step 1800: 0.228663\n",
      "Minibatch accuracy: 93.8%\n",
      "Validation accuracy: 84.6%\n",
      "Minibatch loss at step 2000: 0.368098\n",
      "Minibatch accuracy: 87.5%\n",
      "Validation accuracy: 85.5%\n",
      "Minibatch loss at step 2200: 1.226765\n",
      "Minibatch accuracy: 68.8%\n",
      "Validation accuracy: 84.1%\n",
      "Minibatch loss at step 2400: 0.107882\n",
      "Minibatch accuracy: 100.0%\n",
      "Validation accuracy: 85.3%\n",
      "Minibatch loss at step 2600: 0.826793\n",
      "Minibatch accuracy: 81.2%\n",
      "Validation accuracy: 85.3%\n",
      "Minibatch loss at step 2800: 0.329221\n",
      "Minibatch accuracy: 87.5%\n",
      "Validation accuracy: 86.3%\n",
      "Minibatch loss at step 3000: 0.368162\n",
      "Minibatch accuracy: 87.5%\n",
      "Validation accuracy: 86.1%\n",
      "Minibatch loss at step 3200: 0.706859\n",
      "Minibatch accuracy: 81.2%\n",
      "Validation accuracy: 86.4%\n",
      "Minibatch loss at step 3400: 0.481837\n",
      "Minibatch accuracy: 87.5%\n",
      "Validation accuracy: 86.5%\n",
      "Minibatch loss at step 3600: 0.207919\n",
      "Minibatch accuracy: 100.0%\n",
      "Validation accuracy: 86.8%\n",
      "Minibatch loss at step 3800: 0.372077\n",
      "Minibatch accuracy: 81.2%\n",
      "Validation accuracy: 86.2%\n",
      "Minibatch loss at step 4000: 0.232155\n",
      "Minibatch accuracy: 93.8%\n",
      "Validation accuracy: 86.0%\n",
      "Minibatch loss at step 4200: 0.746712\n",
      "Minibatch accuracy: 81.2%\n",
      "Validation accuracy: 86.9%\n",
      "Minibatch loss at step 4400: 0.025317\n",
      "Minibatch accuracy: 100.0%\n",
      "Validation accuracy: 87.2%\n",
      "Minibatch loss at step 4600: 0.234084\n",
      "Minibatch accuracy: 93.8%\n",
      "Validation accuracy: 87.2%\n",
      "Minibatch loss at step 4800: 0.030294\n",
      "Minibatch accuracy: 100.0%\n",
      "Validation accuracy: 87.7%\n",
      "Minibatch loss at step 5000: 0.585974\n",
      "Minibatch accuracy: 81.2%\n",
      "Validation accuracy: 86.8%\n",
      "Minibatch loss at step 5200: 0.675546\n",
      "Minibatch accuracy: 81.2%\n",
      "Validation accuracy: 87.4%\n",
      "Minibatch loss at step 5400: 0.514829\n",
      "Minibatch accuracy: 81.2%\n",
      "Validation accuracy: 87.2%\n",
      "Minibatch loss at step 5600: 0.401657\n",
      "Minibatch accuracy: 87.5%\n",
      "Validation accuracy: 87.9%\n",
      "Minibatch loss at step 5800: 0.304066\n",
      "Minibatch accuracy: 87.5%\n",
      "Validation accuracy: 87.8%\n",
      "Minibatch loss at step 6000: 0.384240\n",
      "Minibatch accuracy: 81.2%\n",
      "Validation accuracy: 83.6%\n",
      "Minibatch loss at step 6200: 0.278505\n",
      "Minibatch accuracy: 87.5%\n",
      "Validation accuracy: 88.2%\n",
      "Minibatch loss at step 6400: 0.210025\n",
      "Minibatch accuracy: 93.8%\n",
      "Validation accuracy: 87.9%\n",
      "Minibatch loss at step 6600: 0.483855\n",
      "Minibatch accuracy: 87.5%\n",
      "Validation accuracy: 88.2%\n",
      "Minibatch loss at step 6800: 0.456803\n",
      "Minibatch accuracy: 81.2%\n",
      "Validation accuracy: 88.1%\n",
      "Minibatch loss at step 7000: 0.391746\n",
      "Minibatch accuracy: 81.2%\n",
      "Validation accuracy: 88.1%\n",
      "Minibatch loss at step 7200: 0.021722\n",
      "Minibatch accuracy: 100.0%\n",
      "Validation accuracy: 88.2%\n",
      "Minibatch loss at step 7400: 0.335218\n",
      "Minibatch accuracy: 93.8%\n",
      "Validation accuracy: 88.2%\n",
      "Minibatch loss at step 7600: 0.189670\n",
      "Minibatch accuracy: 100.0%\n",
      "Validation accuracy: 88.0%\n",
      "Minibatch loss at step 7800: 0.160095\n",
      "Minibatch accuracy: 100.0%\n",
      "Validation accuracy: 88.3%\n",
      "Minibatch loss at step 8000: 0.206127\n",
      "Minibatch accuracy: 93.8%\n",
      "Validation accuracy: 88.3%\n",
      "Minibatch loss at step 8200: 0.166582\n",
      "Minibatch accuracy: 93.8%\n",
      "Validation accuracy: 88.5%\n",
      "Minibatch loss at step 8400: 0.358086\n",
      "Minibatch accuracy: 87.5%\n",
      "Validation accuracy: 88.2%\n",
      "Minibatch loss at step 8600: 0.098657\n",
      "Minibatch accuracy: 93.8%\n",
      "Validation accuracy: 88.4%\n",
      "Minibatch loss at step 8800: 0.238908\n",
      "Minibatch accuracy: 93.8%\n",
      "Validation accuracy: 88.4%\n",
      "Minibatch loss at step 9000: 0.329803\n",
      "Minibatch accuracy: 87.5%\n",
      "Validation accuracy: 88.4%\n",
      "Minibatch loss at step 9200: 0.370952\n",
      "Minibatch accuracy: 87.5%\n",
      "Validation accuracy: 88.4%\n",
      "Minibatch loss at step 9400: 0.094366\n",
      "Minibatch accuracy: 93.8%\n",
      "Validation accuracy: 88.3%\n",
      "Minibatch loss at step 9600: 0.061244\n",
      "Minibatch accuracy: 100.0%\n",
      "Validation accuracy: 88.5%\n",
      "Minibatch loss at step 9800: 0.444588\n",
      "Minibatch accuracy: 87.5%\n",
      "Validation accuracy: 88.5%\n",
      "Minibatch loss at step 10000: 0.342206\n",
      "Minibatch accuracy: 81.2%\n",
      "Validation accuracy: 88.4%\n",
      "Minibatch loss at step 10200: 0.540451\n",
      "Minibatch accuracy: 81.2%\n",
      "Validation accuracy: 88.8%\n",
      "Minibatch loss at step 10400: 0.550295\n",
      "Minibatch accuracy: 87.5%\n",
      "Validation accuracy: 88.5%\n",
      "Minibatch loss at step 10600: 0.254105\n",
      "Minibatch accuracy: 93.8%\n",
      "Validation accuracy: 88.6%\n",
      "Minibatch loss at step 10800: 0.443997\n",
      "Minibatch accuracy: 87.5%\n",
      "Validation accuracy: 88.9%\n",
      "Minibatch loss at step 11000: 0.096812\n",
      "Minibatch accuracy: 100.0%\n",
      "Validation accuracy: 88.8%\n",
      "Minibatch loss at step 11200: 0.317754\n",
      "Minibatch accuracy: 87.5%\n",
      "Validation accuracy: 88.7%\n",
      "Minibatch loss at step 11400: 0.059269\n",
      "Minibatch accuracy: 100.0%\n",
      "Validation accuracy: 89.0%\n",
      "Minibatch loss at step 11600: 0.102911\n",
      "Minibatch accuracy: 100.0%\n",
      "Validation accuracy: 88.7%\n",
      "Minibatch loss at step 11800: 0.269855\n",
      "Minibatch accuracy: 93.8%\n",
      "Validation accuracy: 88.9%\n",
      "Minibatch loss at step 12000: 0.251514\n",
      "Minibatch accuracy: 93.8%\n",
      "Validation accuracy: 89.0%\n",
      "Minibatch loss at step 12200: 0.172166\n",
      "Minibatch accuracy: 93.8%\n",
      "Validation accuracy: 88.9%\n",
      "Minibatch loss at step 12400: 0.250988\n",
      "Minibatch accuracy: 93.8%\n",
      "Validation accuracy: 89.0%\n",
      "Minibatch loss at step 12600: 0.229203\n",
      "Minibatch accuracy: 100.0%\n",
      "Validation accuracy: 88.9%\n",
      "Minibatch loss at step 12800: 0.222736\n",
      "Minibatch accuracy: 87.5%\n",
      "Validation accuracy: 88.8%\n",
      "Minibatch loss at step 13000: 0.333597\n",
      "Minibatch accuracy: 93.8%\n",
      "Validation accuracy: 88.9%\n",
      "Minibatch loss at step 13200: 0.007365\n",
      "Minibatch accuracy: 100.0%\n",
      "Validation accuracy: 89.0%\n",
      "Minibatch loss at step 13400: 0.847231\n",
      "Minibatch accuracy: 81.2%\n",
      "Validation accuracy: 89.3%\n",
      "Minibatch loss at step 13600: 0.871870\n",
      "Minibatch accuracy: 68.8%\n",
      "Validation accuracy: 89.2%\n",
      "Minibatch loss at step 13800: 0.536240\n",
      "Minibatch accuracy: 81.2%\n",
      "Validation accuracy: 89.0%\n",
      "Minibatch loss at step 14000: 0.568140\n",
      "Minibatch accuracy: 81.2%\n",
      "Validation accuracy: 89.3%\n",
      "Minibatch loss at step 14200: 0.124767\n",
      "Minibatch accuracy: 100.0%\n",
      "Validation accuracy: 89.5%\n",
      "Minibatch loss at step 14400: 0.107394\n",
      "Minibatch accuracy: 93.8%\n",
      "Validation accuracy: 89.5%\n",
      "Minibatch loss at step 14600: 0.605621\n",
      "Minibatch accuracy: 87.5%\n",
      "Validation accuracy: 89.3%\n",
      "Minibatch loss at step 14800: 0.084688\n",
      "Minibatch accuracy: 93.8%\n",
      "Validation accuracy: 89.1%\n",
      "Minibatch loss at step 15000: 0.889330\n",
      "Minibatch accuracy: 75.0%\n",
      "Validation accuracy: 89.4%\n",
      "Minibatch loss at step 15200: 0.603864\n",
      "Minibatch accuracy: 87.5%\n",
      "Validation accuracy: 89.3%\n",
      "Minibatch loss at step 15400: 0.094826\n",
      "Minibatch accuracy: 100.0%\n",
      "Validation accuracy: 88.8%\n",
      "Minibatch loss at step 15600: 0.488690\n",
      "Minibatch accuracy: 87.5%\n",
      "Validation accuracy: 89.2%\n",
      "Minibatch loss at step 15800: 0.599536\n",
      "Minibatch accuracy: 81.2%\n",
      "Validation accuracy: 89.0%\n",
      "Minibatch loss at step 16000: 0.063984\n",
      "Minibatch accuracy: 100.0%\n",
      "Validation accuracy: 89.0%\n",
      "Minibatch loss at step 16200: 0.764722\n",
      "Minibatch accuracy: 87.5%\n",
      "Validation accuracy: 89.3%\n",
      "Minibatch loss at step 16400: 0.241921\n",
      "Minibatch accuracy: 87.5%\n",
      "Validation accuracy: 89.3%\n",
      "Minibatch loss at step 16600: 0.509761\n",
      "Minibatch accuracy: 87.5%\n",
      "Validation accuracy: 89.3%\n",
      "Minibatch loss at step 16800: 0.048411\n",
      "Minibatch accuracy: 100.0%\n",
      "Validation accuracy: 89.4%\n",
      "Minibatch loss at step 17000: 0.083273\n",
      "Minibatch accuracy: 93.8%\n",
      "Validation accuracy: 89.5%\n",
      "Minibatch loss at step 17200: 0.009486\n",
      "Minibatch accuracy: 100.0%\n",
      "Validation accuracy: 89.4%\n",
      "Minibatch loss at step 17400: 0.261492\n",
      "Minibatch accuracy: 93.8%\n",
      "Validation accuracy: 89.1%\n",
      "Minibatch loss at step 17600: 0.248504\n",
      "Minibatch accuracy: 93.8%\n",
      "Validation accuracy: 89.5%\n",
      "Minibatch loss at step 17800: 0.133734\n",
      "Minibatch accuracy: 93.8%\n",
      "Validation accuracy: 89.6%\n",
      "Minibatch loss at step 18000: 0.013869\n",
      "Minibatch accuracy: 100.0%\n",
      "Validation accuracy: 89.6%\n",
      "Minibatch loss at step 18200: 0.618079\n",
      "Minibatch accuracy: 87.5%\n",
      "Validation accuracy: 89.7%\n",
      "Minibatch loss at step 18400: 0.499922\n",
      "Minibatch accuracy: 87.5%\n",
      "Validation accuracy: 89.4%\n",
      "Minibatch loss at step 18600: 0.380934\n",
      "Minibatch accuracy: 93.8%\n",
      "Validation accuracy: 89.8%\n",
      "Minibatch loss at step 18800: 0.175606\n",
      "Minibatch accuracy: 93.8%\n",
      "Validation accuracy: 89.6%\n",
      "Minibatch loss at step 19000: 0.073888\n",
      "Minibatch accuracy: 100.0%\n",
      "Validation accuracy: 89.6%\n",
      "Minibatch loss at step 19200: 0.380497\n",
      "Minibatch accuracy: 87.5%\n",
      "Validation accuracy: 89.5%\n",
      "Minibatch loss at step 19400: 0.431003\n",
      "Minibatch accuracy: 93.8%\n",
      "Validation accuracy: 89.8%\n",
      "Minibatch loss at step 19600: 0.330928\n",
      "Minibatch accuracy: 87.5%\n",
      "Validation accuracy: 89.7%\n",
      "Minibatch loss at step 19800: 0.014386\n",
      "Minibatch accuracy: 100.0%\n",
      "Validation accuracy: 89.4%\n",
      "Minibatch loss at step 20000: 0.758873\n",
      "Minibatch accuracy: 75.0%\n",
      "Validation accuracy: 89.8%\n",
      "Test accuracy: 95.2%\n"
     ]
    }
   ],
   "source": [
    "num_steps = 20001\n",
    "\n",
    "with tf.Session(graph=graph) as session:\n",
    "    tf.initialize_all_variables().run()\n",
    "    print('Initialized')\n",
    "    for step in range(num_steps):\n",
    "        offset = (step * batch_size) % (train_labels.shape[0] - batch_size)\n",
    "        batch_data = train_dataset[offset:(offset + batch_size), :, :, :]\n",
    "        batch_labels = train_labels[offset:(offset + batch_size), :]\n",
    "        feed_dict = {tf_train_dataset : batch_data, tf_train_labels : batch_labels}\n",
    "        _, l, predictions = session.run(\n",
    "          [optimizer, loss, train_prediction], feed_dict=feed_dict)\n",
    "        if (step % 200 == 0):\n",
    "            print('Minibatch loss at step %d: %f' % (step, l))\n",
    "            print('Minibatch accuracy: %.1f%%' % accuracy(predictions, batch_labels))\n",
    "            print('Validation accuracy: %.1f%%' % accuracy(valid_prediction.eval(), valid_labels))\n",
    "    print('Test accuracy: %.1f%%' % accuracy(test_prediction.eval(), test_labels))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "colab": {
   "default_view": {},
   "name": "4_convolutions.ipynb",
   "provenance": [],
   "version": "0.3.2",
   "views": {}
  },
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
